package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.vo.WxGoodsSpecificationVo;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.time.LocalDateTime.now;


@Service
public class MarketGoodsServiceImpl implements MarketGoodsService {

    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketCategoryMapper categoryMapper;

    @Autowired
    MarketGoodsAttributeMapper attributeMapper;

    @Autowired
    MarketBrandMapper brandMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;

    @Autowired
    MarketGrouponMapper grouponMapper;

    @Autowired
    MarketIssueMapper issueMapper;

    @Autowired
    MarketGoodsProductMapper productMapper;

    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;

    @Autowired
    MarketCollectMapper collectMapper;

    @Autowired
    MarketSearchHistoryMapper searchHistoryMapper;

    @Autowired
    MarketFootprintMapper footprintMapper;


    @Override
    public int count() {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.or().andIsOnSaleEqualTo(true).andDeletedEqualTo(false);
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(goodsExample);
        return marketGoods.size();
    }

    /**
     * 先判断是一级目录还是二级目录
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> category(Integer id) {
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        categoryExample.or().andIdEqualTo(id).andDeletedEqualTo(false);
        MarketCategory clickCategory = categoryMapper.selectOneByExample(categoryExample);
        Integer pid = clickCategory.getPid();

        Map<String, Object> result = new HashMap<>();

        if (pid == 0) {
            //一级目录
            MarketCategoryExample categoryExampleL1 = new MarketCategoryExample();
            categoryExampleL1.or().andPidEqualTo(id);
            MarketCategory currentCategory = categoryMapper.selectOneByExample(categoryExampleL1);
            List<MarketCategory> brotherCategory = categoryMapper.selectByExample(categoryExampleL1);

            result.put("brotherCategory", brotherCategory);
            result.put("currentCategory", currentCategory);
            result.put("parentCategory", clickCategory);
            return result;
        } else {
            //二级目录
            MarketCategoryExample categoryExampleL2 = new MarketCategoryExample();
            categoryExampleL2.or().andIdEqualTo(pid).andDeletedEqualTo(false);
            MarketCategory parentCategory = categoryMapper.selectOneByExample(categoryExampleL2);

            MarketCategoryExample example = new MarketCategoryExample();
            example.or().andPidEqualTo(pid).andDeletedEqualTo(false);
            List<MarketCategory> brotherCategory = categoryMapper.selectByExample(example);

            result.put("brotherCategory", brotherCategory);
            result.put("currentCategory", clickCategory);
            result.put("parentCategory", parentCategory);
            return result;
        }

    }

    @Override
    public Map<String, Object> list(Integer categoryId, Integer page, Integer limit) {


        MarketCategoryExample categoryExample = new MarketCategoryExample();
        //filterCategory:所有二级目录
        categoryExample.or().andPidNotEqualTo(0).andDeletedEqualTo(false);
        List<MarketCategory> categoryList = categoryMapper.selectByExample(categoryExample);
        List<MarketCategory> filterCategoryList = new ArrayList<>();
        for (int i = 0; i < 16; i++) {
            MarketCategory category = categoryList.get(i);
            filterCategoryList.add(category);
        }

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.or().andCategoryIdEqualTo(categoryId);

        PageHelper.startPage(page, limit);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample);

        Map<String, Object> result = new HashMap<>();
        result.put("filterCategoryList", filterCategoryList);
        result.put("list", goodsList);

        return result;

    }

    @Override
    public Map<String, Object> listBySearch(String keyword, Integer page, Integer limit, String sort, String order,Integer categoryId) {
        // searchhistory里是否有传入的keyword
        boolean isExist = false;
        MarketSearchHistoryExample marketSearchHistoryExample = new MarketSearchHistoryExample();
        marketSearchHistoryExample.or().andDeletedEqualTo(false);
        List<MarketSearchHistory> marketSearchHistories = searchHistoryMapper.selectByExample(marketSearchHistoryExample);
        for (MarketSearchHistory marketSearchHistory : marketSearchHistories) {
            String keyword1 = marketSearchHistory.getKeyword();
            if (keyword.equals(keyword1)) {
                MarketSearchHistoryExample searchHistoryExample = new MarketSearchHistoryExample();
                searchHistoryExample.or().andKeywordEqualTo(keyword);
                // 新建一个MarketSearchHistory，
                MarketSearchHistory searchHistory = new MarketSearchHistory();
                searchHistory.setUpdateTime(now());
                searchHistoryMapper.updateByExampleSelective(searchHistory, searchHistoryExample);
                isExist = true;
            }

        }

        if (!isExist) {
            // todo keyword插入到search_history
            MarketSearchHistory searchHistory = new MarketSearchHistory();
            searchHistory.setUserId(1);
            searchHistory.setKeyword(keyword);
            searchHistory.setAddTime(now());
            searchHistory.setUpdateTime(now());
            searchHistory.setFrom("wx");
            searchHistory.setDeleted(false);
            // searchHistory.
            searchHistoryMapper.insert(searchHistory);

        }

        Map<String, Object> result = new HashMap<>();
        //分类
        if(categoryId != 0){
            MarketGoodsExample goodsExample = new MarketGoodsExample();
            goodsExample.or().andNameLike("%" + keyword + "%").andCategoryIdEqualTo(categoryId);
            goodsExample.setOrderByClause(sort + " " + order);
            PageHelper.startPage(page, limit);
            List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample);
            result.put("list", goodsList);
        }

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.or().andNameLike("%" + keyword + "%");

        goodsExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample);

        //获取filterCategoryList
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        List<MarketCategory> filterCategoryList = new ArrayList<>();
        for (MarketGoods goods : goodsList) {
            Integer cId = goods.getCategoryId();
            categoryExample.or().andIdEqualTo(cId);
            MarketCategory category = categoryMapper.selectOneByExample(categoryExample);
            //去重
            if (!filterCategoryList.contains(category)) {
                filterCategoryList.add(category);
            }
        }

        if(categoryId == 0) {
            result.put("list", goodsList);
        }
        result.put("filterCategoryList", filterCategoryList);
        return result;
    }

    @Override
    public Map<String, Object> detail(Integer id, Integer userId) {

        if (userId != null) {
            //获取footprints表里的所有的该用户的goodsId
            MarketFootprintExample footprintExample1 = new MarketFootprintExample();
            footprintExample1.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
            List<MarketFootprint> footprints = footprintMapper.selectByExample(footprintExample1);
            List<Integer> goodsId = new ArrayList<>();
            for (MarketFootprint footprint : footprints) {
                goodsId.add(footprint.getGoodsId());
            }

            // todo 商品插入到足迹表中
            MarketFootprint footprint = new MarketFootprint();
            if (goodsId.contains(id)) {
                //足迹表里已有商品，只需修改它的updatetime
                MarketFootprintExample footprintExample = new MarketFootprintExample();
                footprintExample.or().andGoodsIdEqualTo(id);
                footprint.setUpdateTime(now());
                footprintMapper.updateByExampleSelective(footprint, footprintExample);
            } else {
                footprint.setUserId(userId);
                footprint.setGoodsId(id);
                footprint.setAddTime(now());
                footprint.setUpdateTime(now());
                footprint.setDeleted(false);
                footprintMapper.insert(footprint);
            }
        }

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.or().andIdEqualTo(id).andDeletedEqualTo(false);
        MarketGoods goods = goodsMapper.selectOneByExampleWithBLOBs(goodsExample);

        Map<String, Object> result = new HashMap<>();

        //attribute
        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        attributeExample.or().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGoodsAttribute> attributes = attributeMapper.selectByExample(attributeExample);

        //brand
        Integer brandId = goods.getBrandId();
        MarketBrandExample brandExample = new MarketBrandExample();
        brandExample.or().andIdEqualTo(brandId).andDeletedEqualTo(false);
        MarketBrand brand = brandMapper.selectOneByExample(brandExample);

        //comment
        MarketCommentExample commentExample = new MarketCommentExample();
        commentExample.or().andValueIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketComment> comments = commentMapper.selectByExample(commentExample);
        List<MarketComment> commentList = new ArrayList<>();
        if (comments.size() < 2) {
            commentList.addAll(comments);
        } else {
            for (int i = 0; i < 2; i++) {
                MarketComment comment = comments.get(i);
                commentList.add(comment);
            }
        }
        Map<String, Object> commentsMap = new HashMap<>();
        commentsMap.put("data", commentList);
        commentsMap.put("count", comments.size());

        // groupon  根据id匹配order_goods表中的goodsId, 再用orderId匹配groupon表中的数据
        List<MarketGroupon> grouponArrayList = new ArrayList<>();
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        orderGoodsExample.or().andGoodsIdEqualTo(id);
        List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (MarketOrderGoods marketOrderGoods : orderGoodsList) {
            Integer orderId = marketOrderGoods.getOrderId();
            MarketGrouponExample grouponExample = new MarketGrouponExample();
            grouponExample.or().andOrderIdEqualTo(orderId);
            MarketGroupon groupon = grouponMapper.selectOneByExample(grouponExample);
            grouponArrayList.add(groupon);
        }

        //issue
        MarketIssueExample issueExample = new MarketIssueExample();
        List<MarketIssue> issueList = issueMapper.selectByExample(issueExample);

        //productList
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        productExample.or().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGoodsProduct> productList = productMapper.selectByExample(productExample);

        //specificationList
        WxGoodsSpecificationVo specificationVo1 = getSpecificationVo(id, "规格");
        WxGoodsSpecificationVo specificationVo2 = getSpecificationVo(id, "颜色");
        List<WxGoodsSpecificationVo> specificationVoList = new ArrayList<>();
        if (specificationVo1.getName() != null) {
            specificationVoList.add(specificationVo1);
        }
        if (specificationVo2.getName() != null) {
            specificationVoList.add(specificationVo2);
        }

        // userHasCollect 用户是否已经收藏, 通过collect表中的valueId进行匹配
        MarketCollectExample marketCollectExample = new MarketCollectExample();
        marketCollectExample.or().andValueIdEqualTo(id);
        MarketCollect marketCollect = collectMapper.selectOneByExample(marketCollectExample);
        if (marketCollect == null) {
            result.put("userHasCollect", 0);
        } else {
            Byte collectType = marketCollect.getType();
            result.put("userHasCollect", collectType);
        }

        result.put("attribute", attributes);
        result.put("brand", brand);
        result.put("comment", commentsMap);
        result.put("groupon", grouponArrayList);
        result.put("info", goods);
        result.put("issue", issueList);
        result.put("productList", productList);
        result.put("share", false);
        result.put("shareImage", "");
        result.put("specificationList", specificationVoList);

        return result;
    }

    @Override
    public List<MarketGoods> related(Integer id) {

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.or().andIdEqualTo(id).andDeletedEqualTo(false);
        MarketGoods goods = goodsMapper.selectOneByExample(goodsExample);
        Integer categoryId = goods.getCategoryId();
        MarketGoodsExample goodsExample1 = new MarketGoodsExample();
        goodsExample1.or().andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);
        PageHelper.startPage(1, 6);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample1);

        return goodsList;
    }

    @Override
    public Map<String, Object> ListByIsNew(Integer page, Integer limit, String sort, String order) {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.or().andIsNewEqualTo(true).andDeletedEqualTo(false);

        goodsExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample);

        MarketCategoryExample categoryExample = new MarketCategoryExample();
        List<MarketCategory> filterCategoryList = new ArrayList<>();
        for (MarketGoods goods : goodsList) {
            Integer categoryId = goods.getCategoryId();
            categoryExample.or().andIdEqualTo(categoryId);
            MarketCategory category = categoryMapper.selectOneByExample(categoryExample);
            //去重
            if (!filterCategoryList.contains(category)) {
                filterCategoryList.add(category);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("list", goodsList);
        result.put("filterCategoryList", filterCategoryList);
        return result;
    }

    @Override
    public Map<String, Object> ListByIsHot(Integer page, Integer limit, String sort, String order) {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.or().andIsHotEqualTo(true).andDeletedEqualTo(false);

        goodsExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample);

        MarketCategoryExample categoryExample = new MarketCategoryExample();
        List<MarketCategory> filterCategoryList = new ArrayList<>();
        for (MarketGoods goods : goodsList) {
            Integer categoryId = goods.getCategoryId();
            categoryExample.or().andIdEqualTo(categoryId);
            MarketCategory category = categoryMapper.selectOneByExample(categoryExample);
            //去重
            if (!filterCategoryList.contains(category)) {
                filterCategoryList.add(category);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("list", goodsList);
        result.put("filterCategoryList", filterCategoryList);
        return result;
    }

    @Override
    public Map<String, Object> ListByBrandId(Integer brandId, Integer page, Integer limit) {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.or().andBrandIdEqualTo(brandId).andDeletedEqualTo(false);

        PageHelper.startPage(page, limit);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample);

        MarketCategoryExample categoryExample = new MarketCategoryExample();
        List<MarketCategory> filterCategoryList = new ArrayList<>();
        for (MarketGoods goods : goodsList) {
            Integer categoryId = goods.getCategoryId();
            categoryExample.or().andIdEqualTo(categoryId);
            MarketCategory category = categoryMapper.selectOneByExample(categoryExample);
            //去重
            if (!filterCategoryList.contains(category)) {
                filterCategoryList.add(category);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("list", goodsList);
        result.put("filterCategoryList", filterCategoryList);
        return result;
    }

    public WxGoodsSpecificationVo getSpecificationVo(Integer id, String name) {
        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        specificationExample.or().andGoodsIdEqualTo(id).andSpecificationEqualTo(name).andDeletedEqualTo(false);
        List<MarketGoodsSpecification> specificationList = specificationMapper.selectByExample(specificationExample);

        WxGoodsSpecificationVo specificationVo = new WxGoodsSpecificationVo();
        if (specificationList.size() != 0) {
            specificationVo.setName(name);
            specificationVo.setValueList(specificationList);
        }
        return specificationVo;
    }
}
